<template>
  <view class="viewport">
    <!-- 自定义导航栏 -->
    <CustomNavbar />
    <!-- 滚动容器 -->
    <scroll-view
      enable-back-to-top
      refresher-enabled
      @refresherrefresh="onRefresherrefresh"
      :refresher-triggered="isTriggered"
      @scrolltolower="onScrolltolower"
      class="scroll-view"
      scroll-y
    >
      <u-loading-page :loading="true" v-if="isLoading" loading-text="正在加载···"></u-loading-page>
      <template v-else>
        <!-- 自定义轮播图 -->
        <BannerSwiper :list="bannerList" />
        <!-- 分类面板 -->
        <CategoryPanel :list="categoryList" />
        <!-- 猜你喜欢 -->
        <GuessLike ref="guessRef" />
      </template>
    </scroll-view>
  </view>
</template>
<script setup lang="ts">
import { getHomeBannerAPI, getHomeCategoryAPI } from '@/services/home'
import { onLoad } from '@dcloudio/uni-app'
import { ref } from 'vue'
import CustomNavbar from './components/CustomNavbar.vue'
import CategoryPanel from './components/CategoryPanel.vue'
import BannerSwiper from '@/components/BannerSwiper.vue'
import GuessLike from '@/components/GuessLike.vue'

const guessRef = ref(GuessLike)

// 获取轮播图数据
const bannerList = ref<any[]>([])
const getHomeBannerData = async () => {
  const res = await getHomeBannerAPI()
  bannerList.value = res.data
}

// 获取前台分类数据
const categoryList = ref<any[]>([])
const getHomeCategoryData = async () => {
  const res = await getHomeCategoryAPI({
    parentId: 0,
  })
  categoryList.value = res.data
}

// 是否加载中标记
const isLoading = ref(false)

// 页面加载
onLoad(async () => {
  isLoading.value = true
  await Promise.all([getHomeBannerData(), getHomeCategoryData()])
  isLoading.value = false
})

// 当前下拉刷新状态
const isTriggered = ref(false)
// 自定义下拉刷新被触发
const onRefresherrefresh = async () => {
  // 开始动画
  isTriggered.value = true
  // 重置猜你喜欢组件数据
  guessRef.value!.resetData()
  await Promise.all([getHomeBannerData(), getHomeCategoryData(), guessRef.value!.getMore()])
  // 关闭动画
  isTriggered.value = false
}

const onScrolltolower = async () => {
  guessRef.value?.getMore()
}
</script>

<style scoped lang="scss">
page {
  background-color: #f7f7f7;
  height: 100%;
  overflow: hidden;
}

.viewport {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.scroll-view {
  flex: 1;
  overflow: hidden;
}
</style>
